//
//  HLCommentListController.m
//  HLAerospace
//
//  Created by hulian-ios on 17/9/12.
//  Copyright © 2017年 hulian-LB. All rights reserved.
//

#import "HLCommentListController.h"
#import "HLDiscussCell.h"
#import "HLCourseDiscuss.h"
#import <MJExtension/MJExtension.h>
#import <MJRefresh/MJRefresh.h>
#import "HttpRequestManager.h"
#import "MBProgressHUD+HL.h"
#import "HLCourseComment.h"
#import "HLUserInfo.h"
#import "HLCommentCell.h"
#import "HLStartQusetionViewController.h"

#define kPageLimit 10

@interface HLCommentListController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSUInteger _curren_page;
}
@property (nonatomic ,strong) UITableView  *tableView;
/** 顶部视图  */
@property (nonatomic ,strong) UIView *topView;
/** Bottom 视图  */
@property (nonatomic ,strong) UIView *bottomView;
/** dataSource  */
@property (nonatomic ,strong) NSMutableArray *dataSource;

@end

@implementation HLCommentListController

- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (UIView *)topView
{
    if (!_topView) {
        HLDiscussCell *topView = [[HLDiscussCell alloc]init];
        topView.courseDiscuss = self.courseDiscuss;
        topView.contentView.backgroundColor = [UIColor whiteColor];
        topView.line.hidden = YES;
        topView.height = self.courseDiscuss.cellHeight;
        _topView = topView;
    }
    return _topView;
}

- (UIView *)bottomView
{
    if (!_bottomView) {
        CGFloat bottomH = IS_IPHONE_5 ? 44 : 50;
        _bottomView = [[UIView alloc] init];
        _bottomView.frame = CGRectMake(0, ScreenHeight - bottomH, ScreenWidth, bottomH);
        _bottomView.backgroundColor = [UIColor whiteColor];
        
        UIButton *replyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        replyButton.frame = CGRectMake(0.25 * ScreenWidth, (bottomH - 32) * 0.5, 0.5 * ScreenWidth, 32);
        replyButton.backgroundColor = kColorMineBlueBG;
        replyButton.layer.cornerRadius = 15;
        replyButton.clipsToBounds = YES;
        [replyButton setTitle:@"添加评论" forState:UIControlStateNormal];
        [replyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [replyButton addTarget:self action:@selector(replyCommentButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:replyButton];
    }
    return _bottomView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setUI];
}

- (void)setUI
{
    self.navigationItem.title = @"评论";
    self.tableView = ({
       UITableView *tableView =  [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = HLRGB(240, 240, 240);
        tableView.contentInset = UIEdgeInsetsMake(0, 0, (IS_IPHONE_5 ? 44 : 50), 0);
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadRequest)];
        [self.view addSubview:tableView];
        [tableView registerClass:[HLCommentCell class] forCellReuseIdentifier:@"HLCommentCell"];
        tableView;
    });
    _curren_page = 1;
    [self.view addSubview:self.bottomView];
    [self.tableView.mj_footer beginRefreshing];
}

- (void)loadRequest
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
     params[@"title_id"] = self.courseDiscuss.title_id;
     params[@"page"] = @(_curren_page);
     params[@"limit"] = @(kPageLimit);
     params[@"sign"] = [@"getQuesDetail100" signStr];
    __weak typeof(self) weakSelf = self;
    
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:@"getQuesDetail100" parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject){
        weakSelf.tableView.tableHeaderView = self.topView;
        
        if ([responseObject[@"code"] integerValue] == 200) {
            NSArray *tempArray = [HLCourseComment mj_objectArrayWithKeyValuesArray:responseObject[@"data"][0][@"answer_list"]];
            [weakSelf.dataSource addObjectsFromArray:tempArray];
            [weakSelf.tableView reloadData];
            _curren_page++;
            if (tempArray.count < kPageLimit) {
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [weakSelf.tableView.mj_footer endRefreshing];
            }
        }else{
            [weakSelf.tableView.mj_footer endRefreshing];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [weakSelf.tableView.mj_footer endRefreshing];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
}


#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}


- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HLCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HLCommentCell"];
    cell.courseComment = self.dataSource[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HLCourseComment *comment =  self.dataSource[indexPath.row];
    return comment.cellHeight;
}

#pragma mark - Control

- (void)replyCommentButtonClick:(UIButton *)button
{
    HLStartQusetionViewController *start = [[HLStartQusetionViewController alloc] init];
    start.type = HLReplyTypeComment;
    start.commentCompletionBlock = ^{
        /**** 用户评论成功 重新请求 删除数据 ****/
        [self.dataSource removeAllObjects];
        self->_curren_page = 1;
        self.tableView.mj_footer.hidden = NO;
        [self.tableView.mj_footer beginRefreshing];
    };
    start.comment_title_id = self.courseDiscuss.title_id;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:start];
    [self presentViewController:nav animated:YES completion:nil];
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    NSLog(@"%@释放了",self.class);
}

@end
